package com.pc.ipushpin.common.controller;


import com.pc.ipushpin.business.service.IApiRequestRecordService;
import com.pc.ipushpin.business.service.IAppUserService;
import com.pc.ipushpin.common.manager.ClientManager;
import com.pc.ipushpin.common.util.SignValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/interface")
public class ClientiController {
	
	@Resource
	private ClientManager clientManager;
	
	@Resource
	private IAppUserService appUserService;
	
	@Resource
	private IApiRequestRecordService apiRequestRecordService;
	Map<String, Integer> moduleMap = new HashMap<String, Integer>() {
		{
			put("user",1);
			put("label", 2);
			put("store", 3);
		}
	};
	/**
	 * 
	 * @param request
	 * @param version 版本号v1 v2
	 * @param module 模块名称 user news
	 * @param method 方法名称 login
	 * @return
	 */
	@RequestMapping("/{module}/{method}/{version}")
	@ResponseBody
	public Map<String, Object> clientInterface(HttpServletRequest request, @PathVariable String version, @PathVariable String module, @PathVariable String method) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		Map<String, String> mapIn = null;
		Map<String, String> req = null;
		try {
			// 获取接口方法权限
			mapIn = logParams(request);
//			System.err.println("入参："+mapIn);
			if (module == null || method == null || moduleMap.get(module) == null) {
				map.put("code", "106");
				map.put("msg", "系统没有提供这个接口或者没有调用权限");
				map.put("success", false);
				return map;
			}
			// 获取通用参数
			req = getCommonParam(request);
			if (req.get("result") != null) {
				map.put("code", "103");
				map.put("msg", "通用参数缺失");
				map.put("success", false);
				return map;
			}
			
			//测试接口 跳过验签
			if("2018-01-01 12:12:12".equals(mapIn.get("reqtime"))){
				
			}else{
				//判断接口是否已过期  api 不一致
				if(!this.checkToken(request)){
					map.put("code", "114");
					map.put("msg", "抱歉，当前账号已在其他设备登录，请重新登录");
					map.put("success", false);
					return map;
				}
				
				//验签
				/*if(!this.clientValidator(request)){
					map.put("code", "102");
					map.put("msg", "报文验签失败");
					map.put("success", false);
					return map;
				}*/
			}
			map = choiceModule(module, method, version, mapIn, request);

		} catch (Exception e) {
			e.printStackTrace();
			map.put("code", "901");
		}
		//装载msg
		if(!map.containsKey("code")){
			defalultMap(map);
		}
		returnMsg(map);
		//保存报文
		apiRequestRecordService.insertRecord(module, method, version, mapIn.get("terminalType"), mapIn.toString(), map);
	
		return map;
	}
	
	/**
	 * 模块跳转
	 * @param request
	 * @param req:component
	 * @return
	 */
	public Map<String, Object> choiceModule(String module,String method,String version,Map<String, String> mapIn, HttpServletRequest request) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		switch (moduleMap.get(module)) {
			case 1:
				map = clientManager.userModule(method, version, mapIn, request);
				break;
			case 2:
				map = clientManager.labelModule(method, version, mapIn, request);
				break;
			case 3:
				map = clientManager.storeModule(method, version, mapIn, request);
				break;
		default:
			map.put("code", "106");
			map.put("msg", "系统没有提供这个接口或者没有调用权限");
			map.put("success", false);
			break;
		}
		return map;
	}
	
	@SuppressWarnings("rawtypes")
	private Map<String, String> logParams(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		try {
			Enumeration enu = request.getParameterNames();
			while (enu.hasMoreElements()) {
				String paraName = (String) enu.nextElement();
				params.put(paraName, request.getParameter(paraName));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return params;
	}
	/**
	 * 检查接入方与各组件的验签
	 * @param map
	 * @return
	 */
	
	/**
	 * 与组件通讯验签方法
	 * 
	 * @param map
	 * @return
	 */
	public Boolean clientValidator(HttpServletRequest request) {

		// 验签
		Map<String, String> map = logParams(request);
		
		String sign = map.get("sign");
		if (sign == null || "".equals(sign)) {
			return false;
		}
		map.remove("sign");
		try {
			String key = "85950c3da48e217cfd38df167aaa2f78";
			String v_sign = SignValidator.buildSignature(map, key);
			if(v_sign.equals(sign)){
				return true;
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * 检测通用参数-组件调用的接口
	 * @param request
	 * @return
	 */
	private Map<String, String> getCommonParam(HttpServletRequest request) {
			Map<String, String> param = new HashMap<String, String>();
		try {
			
			String terminalType = request.getParameter("terminalType");
			String reqtime = request.getParameter("reqtime");
			String sign = request.getParameter("sign");
			String token = request.getParameter("token");
			if (token == null ||reqtime == null || sign == null || terminalType == null) {
				param.put("result", "1");
				return param;
			}

			param.put("terminalType", terminalType);
			param.put("reqtime", reqtime);
			param.put("sign", sign);
			
		} catch (Exception e) {
			e.printStackTrace();
			param.put("result", "1");
		}
		return param;
	}

	
	/**
	 * 检查token
	 * 
	 * @param map
	 * @return
	 */
	public Boolean checkToken(HttpServletRequest request) {

		// 验签
		Map<String, String> map = logParams(request);
		String token = map.get("token");
		String userId = map.get("userId");
		String  terminalType= map.get("terminalType");
		
		if(!StringUtils.isEmpty(userId)){
			if("iosClient".equals(terminalType) || "androidClient".equals(terminalType)){
				//每次校验token
				String lastToken = appUserService.getUserToken(userId);
				//上次token不为空才校验
				if(!StringUtils.isEmpty(lastToken)){
					if(token.equals(lastToken)){
						//未过期
						return true;
					}else{
						//已过期
						return false;
					}
				}else{
					return true;
				}
			
			}else{
				return true;
			}

		}else{
			return true;
		}
		

	}
	
	
	/**
	 * 返回
	 * @param code
	 * @return
	 */
	public void returnMsg(Map<String, Object> map){
		
		String msg = "";
		String code = map.get("code")+"";
		
		switch(code){
		case "200":
			msg = "处理或操作成功";
			break;
		case "101":
			msg = "请求报文异常";
			break;
		case "102":
			msg = "报文验签失败";
			break;
		case "103":
			msg = "通用参数缺失";
			break;
		case "104":
			msg = "未授权合作账户";
			break;
		case "105":
			msg = "错误的通用参数";
			break;
		case "106":
			msg = "系统没有提供这个接口或者没有调用权限";
			break;
		case "107":
			msg = "业务参数缺失";
			break;
		case "108":
			msg = "错误的业务参数";
			break;
		case "109":
			msg = "未知错误";
			break;
		case "110":
			msg = "网络连接异常";
			break;
		case "111":
			msg = "处理或操作失败";
			break;
		case "112":
			msg = "合作方没有该接口调用权限";
			break;
		case "113":
			msg = "合作方已加入黑名单";
			break;
		case "114":
			msg = "此请求已失效，请更新请求时间";
			break;
		case "116":
			msg = "验证次数过多，该验证码已失效，请重新获取验证码";
			break;
		case "117":
			msg = "输入的验证码有误";
			break;
		case "118":
			msg = "请先获取验证码";
			break;
		case "300":
			msg = "您还没有注册账号，请先进行注册";
			break;
		case "301":
			msg = "已存在该用户";
			break;
		case "302":
			msg = "用户账号或者密码错误，请检查";
			break;
		case "303":
			msg = "登录错误次数过多，已限制登录";
			break;
		case "304":
			msg = "无此用户，请检查";
			break;
		case "305":
			msg = "因网络原因，注册失败，请检查";
			break;
		case "306":
			msg = "用户状态异常";
			break;
		case "307":
			msg = "暂未设置密码 请使用验证码登录";
			break;
		case "308":
			msg = "抱歉，输入原密码有误";
			break;
		case "314":
			msg = "用户授权失败，请重新授权";
			break;
		case "316":
			msg = "session过期，请重新获取";
			break;
		case "317":
			msg = "抱歉，更新用户信息失败";
			break;
		case "361":
			msg = "查询失败";
			break;	
		case "363":
			msg = "网络超时";
			break;
		case "400":
			msg = "暂无数据";
			break;
		case "601":
			msg = "支付异常，请稍后再试";
			break;
		case "603":
			msg = "订单信息不存在";
			break;
		case "605":
			msg = "支付密码错误";
			break;
		case "607":
			msg = "设置支付密码失败，请重试";
			break;
		case "901":
			msg = "系统繁忙，请稍后再试";
			break;
		case "902":
			msg = "其他错误";
			break;
		case "903":
			msg = "抱歉，操作失败";
			break;
//		default:
//			code ="901";
//			msg = "系统繁忙，请稍后再试";
//			break;
				
		}
		if("200".equals(code) || "600".equals(code)){
			map.put("success", true);
		} else{
			map.put("success", false);
		}
		if(map.get("msg") != null){
			msg = map.get("msg")+"";
		}
		map.put("code", code);
		map.put("msg", msg);
	}
	
	public  void defalultMap(Map<String, Object> map) {
		map.put("code", "106");
		map.put("msg", "系统没有提供这个接口或者没有调用权限");
		map.put("success", false);
	}

}
